package com.sscl.baselibrary.utils

import android.bluetooth.BluetoothAdapter
import android.content.Context
import android.content.Intent
import androidx.annotation.IntRange
import androidx.annotation.Size
import java.io.*
import java.nio.charset.Charset
import java.nio.charset.UnsupportedCharsetException
import java.text.DecimalFormat
import java.util.*

/**
 * 数据转换工具类
 *
 * @author pengh
 */
object ConversionUtil {


    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *
     * 公开方法
     *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

    /**
     * 格式化数字为千分位显示；
     *
     * @param number 要格式化的数字
     * @return
     */
    fun formatMicrometer(number: String): String {
        val df: DecimalFormat
        val point = "."
        val pointIndex = number.indexOf(point)
        df = if (pointIndex > 0) {
            when (number.length - pointIndex - 1) {
                0 -> {
                    DecimalFormat("###,##0.")
                }

                1 -> {
                    DecimalFormat("###,##0.0")
                }

                else -> {
                    DecimalFormat("###,##0.00")
                }
            }
        } else {
            DecimalFormat("###,##0")
        }
        val result: Double = try {
            number.toDouble()
        } catch (e: Exception) {
            0.0
        }
        return df.format(result)
    }

    /**
     * 将整数转换成16进制字符串
     *
     * @param i 整数
     * @return 16进制字符串
     */
    fun intToHexStr(i: Int): String {
        return Integer.toHexString(i)
    }

    /**
     * 将字节型数据转换为0~255 (0xFF 即BYTE)
     *
     * @param data data字节型数据
     * @return 无符号的整型
     */
    fun getUnsignedByte(data: Byte): Int {
        return data.toInt() and 0x0FF
    }

    /**
     * 将字节型数据转换为0~65535 (0xFFFF 即 WORD)
     *
     * @param data 字节型数据
     * @return 无符号的整型
     */
    fun getUnsignedShort(data: Short): Int {
        return data.toInt() and 0x0FFFF
    }

    /**
     * 将int数据转换为0~4294967295 (0xFFFFFFFF即DWORD)。
     *
     * @param data int数据
     * @return 无符号的长整型
     */
    fun getUnsignedInt(data: Int): Long {
        //获取最低位
        val lowBit: Int = (1 and data).toByte().toInt()
        //无符号右移一位（无符号数）
        val i: Int = data ushr 1
        //将右移之后的数强转为long之后重新左移回去
        val l: Long = i.toLong() shl 1
        //重新加上低位的值
        return l + lowBit
    }

    /**
     * 将任意对象转为byte数组
     *
     * @param o 任意对象
     * @return byte数组
     */
    fun objectToByteArray(o: Any): ByteArray? {
        var byteArray: ByteArray? = null
        val byteArrayOutputStream = ByteArrayOutputStream()
        var objectOutputStream: ObjectOutputStream? = null
        try {
            objectOutputStream = ObjectOutputStream(byteArrayOutputStream)
            objectOutputStream.writeObject(o)
            byteArray = byteArrayOutputStream.toByteArray()
        } catch (e: IOException) {
            e.printStackTrace()
        } finally {
            if (objectOutputStream != null) {
                try {
                    objectOutputStream.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
        try {
            byteArrayOutputStream.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return byteArray
    }

    /**
     * 将数组类型转为指定的对象
     *
     * @param byteArray 数组类
     * @return T 指定对象
     */
    fun <T : Serializable?> byteArrayToObject(byteArray: ByteArray): T? {
        var o: T? = null
        val byteArrayInputStream = ByteArrayInputStream(byteArray)
        var objectInputStream: ObjectInputStream? = null
        @Suppress("UNCHECKED_CAST")
        try {
            objectInputStream = ObjectInputStream(byteArrayInputStream)
            val readObject = objectInputStream.readObject()
            o = readObject as T?
        } catch (e: IOException) {
            e.printStackTrace()
        } catch (e: ClassNotFoundException) {
            e.printStackTrace()
        } finally {
            if (objectInputStream != null) {
                try {
                    objectInputStream.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
            try {
                byteArrayInputStream.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        return o
    }

    /**
     * 将蓝牙设备地址转为byte数组
     *
     * @param address 设备地址
     * @return byte数组
     */
    fun macAddressStringToByteArray(address: String): ByteArray? {
        if (!BluetoothAdapter.checkBluetoothAddress(address)) {
            return null
        }
        val cacheArray: Array<String> = address.split(":".toRegex(), 6).toTypedArray()
        val bluetoothByteArray = ByteArray(6)
        for (i in cacheArray.indices) {
            val cache: String = cacheArray[i]
            var integer: Int
            try {
                integer = Integer.valueOf(cache, 16)
            } catch (e: NumberFormatException) {
                e.printStackTrace()
                return null
            }
            bluetoothByteArray[i] = integer.toByte()
        }
        return bluetoothByteArray
    }
}